<?php

namespace App\Http\Controllers\Api;

use App\Admin\Actions\Yt\Buttons\CustomsToRefund;
use App\Admin\Actions\Yt\Customs\ContractSubmitAction;
use App\Admin\Actions\Yt\Customs\ContractUploadFilesAction;
use App\Admin\Actions\Yt\Customs\CustomsInvoiceSubmitAction;
//use App\Admin\Actions\Yt\Customs\ExportCustomsFileAction;
use App\Admin\Actions\Yt\ExportSummaryShipAction;
use App\Admin\Actions\Yt\TestAction;
use App\Admin\Actions\Yt\ImportContractAction;
use App\Admin\Grid\Grid;
use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\CustomsContainerDetail;
use App\Models\CustomsExporter;
use App\Models\Delivery;
use App\Models\Suppliers;
use Carbon\Carbon;
use App\Models\CustomsHarbour;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;


class ContractController extends Controller
{

    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '合同管理';

    protected $customsContainer;


    public function __construct(Contract $model)
    {
        $this->model = $model;
    }


    public function index(Request $req)
    {
        $all = $req->all();
        $qry = Contract::query();
        $per_page = $this->getPerPage($req);

        if (isset($all['contract_no'])) {
            $qry->where('contract_no','like', "%{$all['contract_no']}%");
        }
        if (isset($all['contract_date_start'])) {
            $qry->where('contract_date', '>=',$all['contract_date_start']);
        }
        if (isset($all['contract_date_end'])) {
            $qry->where('contract_date', '<=', endDateTime($all['contract_date_end']));
        }
        //出口日期
        if (isset($all['exporter_date_start'])) {
            $qry->where('exporter_date', '>=', $all['exporter_date_start']);
        }
        if (isset($all['exporter_date_end'])) {
            $qry->where('exporter_date', '<=', endDateTime($all['exporter_date_end']));
        }
        if (isset($all['harb_from'])) {
            $qry->where('harb_from', '=', $all['harb_from']);
        }
        if (isset($all['harb_dest'])) {
            $qry->where('harb_dest', '=', $all['harb_dest']);
        }
        if (isset($all['status'])) {
            $qry->where('status', '=', $all['status']);
        }

        $list = $qry->paginate($per_page);
        return $this->resSuccess('', $list);

    }

    // 新增合同
    public function store()
    {
        $all              = request()->all();
        $no               = trim($all['contract_no']);
        $all['boat_date'] = Contract::makeBoatDate($all['date']);
//        $origin = [];

        // 判断：原合同
        $exi = Contract::where('contract_no', $no)->first();
        if ($exi) {
            return $this->resError('合同号码已存在！' . $no);
        }
        $all['created_at']     = Carbon::now()->toDateTimeString();
        $delivery_external_nos = $all['delivery_external_no'];
        $all['delivery_external_no'] = implode(',',array_filter($all['delivery_external_no']));
        $cont = new Contract($all);
        //反向填合同号
        //判断所填订单是否已经填了合同号
        $Delivery = Delivery::query()->whereIn('external_no', $delivery_external_nos)->whereNotNull('contract_no')->get();
        if (!$Delivery->isEmpty()) {
//            admin_error($Delivery->pluck('external_no')->implode(',') . '订单号已经填了合同号,请确认');
            return $this->resError($Delivery->pluck('external_no')->implode(',') . '订单号已经填了合同号,请确认');
        }
        Delivery::query()->whereIn('external_no', $delivery_external_nos)->whereNull('contract_no')->update([
            'contract_no' => $no,
            'updated_at'  => Carbon::now()->toDateTimeString(),
        ]);

        if ($file = request()->file('customs_no_file')) {
            $fileName               = $file->getClientOriginalName();
            $path                   = Storage::putFileAs('contract', $file, $fileName);// public/contract
            $cont->customs_no_file  = $path;
            $all['customs_no_file'] = $path;
        }

        if ($file = request()->file('pass_file')) {
            $fileName         = $file->getClientOriginalName();
            $path             = Storage::putFileAs('contract', $file, $fileName);// public/contract
            $cont->pass_file  = $path;
            $all['pass_file'] = $path;
        }


        // 操作日志
//        $form = $this->form();
//        self::setOrigin($form, $origin);

        if ($cont->save()) {
//            self::saveLog($form, 'contract_no', $cont);
            return $this->resSuccess();
        } else {
            return self::resError();
        }

    }

    // 更新合同
    public function update($id)
    {
        $all              = request()->all();
        $no               = $all['contract_no'];
        $all['boat_date'] = Contract::makeBoatDate($all['date']);
//        $origin = [];

        $cont   = Contract::find($id);
        $origin = $cont->toArray();
        // 判断：原合同号码是否已经关联报关资料
        $exi = CustomsContainerDetail::where('contract_no', $cont->contract_no)
            ->where('cid', '<>', $id)
            ->first();
        if ($exi) {
            return self::resError('原合同号码已在报关资料使用！' . $no);
        }

        // 判断：新合同号
        $exi = Contract::where('contract_no', $no)
            ->where('id', '<>', $id)
            ->first();
        if ($exi) {
            return self::resError('新合同号码已存在！' . $no);
        }
        if ($no != $cont->contract_no){
            Delivery::query()->where('contract_no', $cont->contract_no)->update([
                'contract_no' => $no,
                'updated_at'  => Carbon::now()->toDateTimeString(),
            ]);
        }
        $cont->fill($all);

        if ($file = request()->file('customs_no_file')) {
            $fileName               = $file->getClientOriginalName();
            $path                   = Storage::putFileAs('contract', $file, $fileName);// public/contract
            $cont->customs_no_file  = $path;
            $all['customs_no_file'] = $path;
        }

        if ($file = request()->file('pass_file')) {
            $fileName         = $file->getClientOriginalName();
            $path             = Storage::putFileAs('contract', $file, $fileName);// public/contract
            $cont->pass_file  = $path;
            $all['pass_file'] = $path;
        }

        // 操作日志
//        $form = $this->form();
//        self::setOrigin($form, $origin);
        if ($cont->save()) {
//            self::saveLog($form, 'contract_no', $cont);
            return $this->resSuccess();
        } else {
            return $this->resError();
        }
    }



    /**
     * Make a grid builder.
     *
     * @return Grid
     */

    protected function grid()
    {

        $grid = new Grid(new Contract());
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->like('contract_no', '合同号码');
                $filter->between('contract_date', '合同日期')->date();
                $filter->between('exporter_date', '出口日期')->date();
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('harb_from', '装运地')->select(CustomsHarbour::getFromHarbourList());
                $filter->equal('harb_dest', '卸货地')->select(CustomsHarbour::getDestHarbourList());
                $filter->equal('status', '状态')->select(Contract::CONTRACT_STATUS_MAP);
            });
        });
        if (!empty(request('contract_date')['start']) && !empty(request('contract_date')['end'])) {
            $start_time = date('Y-m-d', strtotime(request('contract_date')['start'])) . ' 00:00:00';
            $end_time   = date('Y-m-d', strtotime(request('contract_date')['end'])) . ' 23:59:59';
            request()->offsetSet('contract_date', ['start' => $start_time, 'end' => $end_time]);
        }

        $grid->model()->orderBy('id', 'desc');
        $grid->fixColumns(3);
        $grid->enableHotKeys();

        $grid->column('id');


        $grid->column('invoice_type', __('开票类型'));
        $grid->column('contract_no', __('合同号码'));
        $grid->column('contract_date', __('合同日期'));
        $grid->column('buyer_id', __('买方'))->display(function ($value) {
            return CustomsExporter::getBuyerList()[$value] ?? '';
        });
//        $grid->column('seller_id', __('卖方'))->display(function ($value) {
//            return CustomsExporter::getSalesList()[$value] ?? '';
//        });
        $grid->column('currency', __('币别'));
        $grid->column('trade_terms', __('贸易条款'));
        $grid->column('payment_type', __('付款条件'));

        $grid->column('harb_from', __('装运地'))->display(function ($value) {
            return CustomsHarbour::getFromHarbourList()[$value] ?? '';
        });
        $grid->column('harb_dest', __('卸货地'))->display(function ($value) {
            return CustomsHarbour::getDestHarbourList()[$value] ?? '';
        });
//        $grid->column('from_area', __('原产国'));
        $grid->column('dest_area', __('目的国'));
        $grid->column('date', __('发票日期(离场日期)'));
        $grid->column('boat_date', __('装运日期'));

        $grid->column('agent_fee', __('代理支付费用'));
        $grid->column('transport_type', __('运输方式'));
//        $grid->column('transport_type', __('运输方式'))->display(function ($value) {
//            return Contract::transportType[$value] ?? '';
//        });

        $url = env('APP_URL');
        $grid->column('bill_no', __('提单号'))->editable();
        $grid->column('bill_no_file', '提单')->display(function ($file) use ($url) {
            if ($file) {
                return "<a class=\"btn btn-default btn-sm\" href=\"$url/$file\" target=\"_blank\">下载</a>";
            } else {
                return "";
            }
        });

        $grid->column('customs_no', __('关单号'))->editable();

        $grid->column('customs_no_file', '报关单')->display(function ($file) use ($url) {
            if ($file) {
                return "<a class=\"btn btn-default btn-sm\" href=\"$url/$file\" target=\"_blank\">下载</a>";
            } else {
                return "";
            }
        });
        // 放行单
        $grid->column('pass_file', '放行单')->display(function ($file) use ($url) {
            if ($file) {
                return "<a class=\"btn btn-default btn-sm\" href=\"$url/$file\" target=\"_blank\">下载</a>";
            } else {
                return "";
            }
        });

        $grid->column('cabinet_no', __('柜号'));
        $grid->column('seal', __('封签'));
        $grid->column('logistics', __('头程物流商'));
        $grid->column('port_fee', __('港杂费'));
        $grid->column('transport_fee', __('内陆运输费'));
        $grid->column('exporter_date', __('出口日期'));
        $grid->column('delivery_external_no', __('订单号'));
        $grid->column('status', __('状态'))->display(function ($val) {
            return Contract::CONTRACT_STATUS_MAP[$val];
        });
//        $grid->actions(function ($actions) {
            // 去掉删除
//            $actions->disableDelete();
            // 去掉编辑
//            $actions->disableEdit();
//            $actions->disableView();
//            $id = $actions->getKey();
//            $actions->add(new CustomsToRefund($id));
//        });

        $this->disableButton(['view','batch_delete']);

        $this->rowButton(new CustomsToRefund());// 查看明细

        $this->toolsButton(new ImportContractAction());
        $this->toolsButton(new ContractUploadFilesAction());// 批量上传文件

        $this->toolsButton(new ContractSubmitAction());// 退税开票通知
        $this->toolsButton(new CustomsInvoiceSubmitAction());


//        $grid->tools(function ($tools) {
//            $tools->append(new TestAction());
//            $tools->append(new ImportContractAction());
//            $tools->append(new ContractUploadFilesAction());// 批量上传文件

//            $tools->batch(function ($batch) {
//                $batch->disableDelete();
//                $batch->add(new ContractSubmitAction()); // 退税开票通知
//                $batch->add(new CustomsInvoiceSubmitAction());

//            });
//        });
        return $grid;


    }



    public function form()
    {
        $form = new Form(new Contract());

        $id = @request()->route()->parameters()['contract'];
//        $form->setAction('/admin/contract/save/' . $id);

        $isImported = 0;
        $form->disableCreatingCheck();
        $form->disableViewCheck();
        $form->tools(function ($actions) {
            $actions->disableView();
        });

        $form->select('invoice_type', '开票类型')
            ->options(Contract::InvoiceType)->default('A');
        $form->column(1 / 2, function ($form) use ($isImported, $id) {
            if (!$form->isCreating()) {
                $isImported = Contract::where('id', '=', $id)->value('is_imported');
                if ($isImported == 1) {
                    $form->text('contract_no', '合同号码')->readonly();
                } else {
                    $form->text('contract_no', '合同号码')->required();
                }
            } else {
                $form->text('contract_no', '合同号码')->required();
            }
            $form->date('contract_date', '合同日期');
            $form->select('buyer_id', '买方')->options(
                CustomsExporter::where('type', CustomsExporter::BUYER)->pluck('name_cn', 'id')
            )->required();
            $form->select('seller_id', '卖方')->options(
                CustomsExporter::where('type', CustomsExporter::SELLER)->pluck('name_cn', 'id')
            )->required();
            $form->select('currency', '币别')->options(
                Contract::Currency
            )->default('USD');

            $form->currency('agent_fee', '支付费用')->symbol('')->default(0);;
            $form->select('transport_type', '运输方式')->options(
                Contract::TransportType
            )->default('FCL');
            $form->currency('transport_fee', '内陆运输费')->symbol('')->default(0);;

            $form->text('bill_no', '提单号')->width('200px');
//            $form->file('bill_no_file', '提单文件')->removable();

            $form->text('customs_no', '关单号')->width('200px');
//            $form->file('customs_no_file', '关单文件')->removable();
//            $form->file('pass_file', '放行单');

            if ($id){
                $form->text('delivery_external_no', '订单号')->readonly();
            }else{
                $form->multipleSelect('delivery_external_no', '订单号')->options(
                    Delivery::query()->whereNull('contract_no')->whereNotNull('external_no')->pluck('external_no', 'external_no')
                )->required();
            }
        });


        $form->column(1 / 2, function ($form) {
            $form->select('trade_terms', '贸易条款')->options(
                Contract::TradeTerms
            )->default('FOB');

            $form->select('payment_type', '付款条件')->options(
                Contract::PaymentType
            )->default('T/T before Shippment');

            $form->select('harb_from', '装运地')->options(
                CustomsHarbour::where('type', CustomsHarbour::START_PORT)->pluck('name', 'id')
            )->required();
            $form->select('harb_dest', '卸货地')->options(
                CustomsHarbour::where('type', CustomsHarbour::DESC_PORT)->pluck('name', 'id')
            )->required();
            $form->select('from_area', '原产国')->options(
                Suppliers::getCountryByDistinct()
            )->default('中国');
            $form->select('dest_area', '目的国')->options(
                CustomsHarbour::getCountryByType(CustomsHarbour::DESC_PORT)
            )->default('美国');

            $form->date('date', '离场日期')->required();
//            $form->date('boat_date', '装运日期')->readonly();
            $form->text('seal', '封签');
            $form->currency('port_fee', '港杂费')->symbol('')->default(0);
            $form->text('cabinet_no', '柜号');
            $form->text('logistics', '头程物流商');

            $form->date('exporter_date', '出口日期')->required();

        });


        return $form;
    }


//    use \App\Traits\OperationLog;






}
